package com.jargonee.activities;

import java.util.Hashtable;

import org.json.JSONObject;

import com.jargonee.threads.BackendThread;
import com.jargonee.threads.BackendThread.BackendThreadMessages;
import com.jargonee.threads.BackendThread.BackendThreadModes;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;

public class JargoneeSearch extends Activity {
	
	// different types of dialogs
	static final int SEARCH_PROGRESS_DIALOG = 0;
	static final int ERROR_DIALOG = 1;
	static final int NO_RESULTS_DIALOG = 2;
	static final int REFRESH_DIALOG = 3;
	
	static final int MAX_SEARCH_RADIUS = 3;
	
	// search parameters
	private int radius;
	private String word;
	private Address address;
	
	// Define the Handler that receives messages from the search thread and update the progress
    final Handler handler = new Handler() { public void handleMessage(Message msg) { handleBackendMessage(msg);}};
    
    /** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// get word, address, and radius
		Bundle extras = getIntent().getExtras();
	    if (extras == null) {
	    	// display error dialog saying no word to search
	    }

	    word = extras.getString("word");
	    radius = extras.getInt("radius", MAX_SEARCH_RADIUS);
	    Parcelable parcelable = extras.getParcelable("address");
	    
	    // check parameters and correct if possible
	    if(parcelable == null || !(parcelable instanceof Address)) {
	    	address = new Address(null);
	    	address.setCountryName("United States");
	    	address.setAdminArea("Some State");
	    	address.setSubAdminArea("Some City");
	    }
	    else
	    	address = (Address)parcelable;
	    if(word == null || word.equals("")) {
	    	// display error dialog saying no word to search
	    }
	    if(radius < 0)
	    	radius = 0;
	    if(radius > 3)
	    	radius = 3;
	    
	    setContentView(R.layout.jargonee_search);
	    
	    submitSearch();
	}
	
	/**
	 * Creates dialogs
	 */
	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		Dialog dialog = null;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch (id) {
		case SEARCH_PROGRESS_DIALOG:
			dialog = ProgressDialog.show(this, "", args.getString("message")+ " Please wait...", true);
			break;
		case ERROR_DIALOG:
			// build alert dialog with error message and ok button
			builder.setMessage(args.getString("message"))
		       .setCancelable(false)
		       .setNeutralButton("Ok", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   removeDialog(ERROR_DIALOG);
		        	   finish();
		           }
		       });
			dialog = builder.create();
			break;
		case NO_RESULTS_DIALOG:
			builder.setMessage(args.getString("message"))
				.setCancelable(false)
				.setNegativeButton("New Search", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   removeDialog(NO_RESULTS_DIALOG);
			        	   finish();
			           }
				})
				.setPositiveButton("Define It", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						removeDialog(NO_RESULTS_DIALOG);
						startInput();
					}
				});
			if(radius != MAX_SEARCH_RADIUS) {
				builder.setNeutralButton("Increase Radius", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   removeDialog(NO_RESULTS_DIALOG);
			        	   increaseRadius();
			           }
				});
			}
			dialog = builder.create();
			break;
		case REFRESH_DIALOG:
			builder.setMessage("Update Results?")
			.setCancelable(false)
			.setNegativeButton("New Search", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   dismissDialog(REFRESH_DIALOG);
		        	   finish();
		           }
				})
				.setPositiveButton("Refresh Results", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dismissDialog(REFRESH_DIALOG);
						submitSearch();
					}
				});
			dialog = builder.create();
			break;
		default:
			break;
		}

		return dialog;
	}
	
	private void handleBackendMessage(Message msg) {
		removeDialog(SEARCH_PROGRESS_DIALOG);
    	switch((BackendThreadMessages)msg.getData().getSerializable("message type")) {
    		case SearchSuccessful:
    			organizeResults((JSONObject)msg.obj);
    			break;
    		case TroubleGettingResults:
    			showDialog(ERROR_DIALOG, msg.getData());
    			break;
    		case NoResultsFound:
    			showDialog(NO_RESULTS_DIALOG, msg.getData());
    			break;
    		default:
    			Bundle bundle = new Bundle();
    			bundle.putString("message", "results received");
    			showDialog(ERROR_DIALOG, bundle);
    			break;
    	}
	}
	
	private void submitSearch() {
		String radiusString;
	    switch(radius) {
	    	case 0:
	    		radiusString = "City wide";
	    		break;
	    	case 1:
	    		radiusString = "State wide";
	    		break;
	    	case 2:
	    		radiusString = "Country wide";
	    		break;
	    	case 3:
	    	default:
	    		radiusString = "World wide";
	    		break;
	    }
	    
	    radiusString += " search for term: " +word+ ".";
	    Bundle bundle = new Bundle();
	    bundle.putString("message", radiusString);
	    showDialog(SEARCH_PROGRESS_DIALOG, bundle);
		
		Hashtable<String,Object> extraParams = new Hashtable<String, Object>();
	    Uri.Builder uriBuilder = new Uri.Builder();
		uriBuilder = uriBuilder.encodedPath(getResources().getString(R.string.jargonee_host) + "service/buzzword/get/");
		extraParams.put("uriBuilder", uriBuilder);
		extraParams.put("distance", "" +radius);
		extraParams.put("word", word);
		extraParams.put("address", address);
	    
	    // start up thread 
		BackendThread thread = new BackendThread(handler, BackendThreadModes.RetrieveLocalResults, extraParams);
		thread.start();
	}
	
	private void increaseRadius() {
		if(radius <= MAX_SEARCH_RADIUS)
			radius++;
		
		submitSearch();
	}
	
	private void startInput() {
		Intent jargoneeInput = new Intent(this, JargoneeInput.class);
		jargoneeInput.putExtra("word", word);
		startActivityForResult(jargoneeInput, 100);
	}
	
	private void organizeResults(JSONObject jsonObject) {
		
		/*try {
			JSONArray localeList = jsonObject.getJSONArray("locales");
			localeList
		}*/
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
		
		boolean submitted = data.getExtras().getBoolean("submitted");
		
		if(submitted) {
			showDialog(REFRESH_DIALOG);
		} else{
			showDialog(NO_RESULTS_DIALOG);
		}
		
	}
	
	

}
